<template>
  <div class="cm-editor-container" ref="editorEl"></div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref, watchEffect } from 'vue'
import * as formatter from 'sql-formatter'

const props = defineProps({
  code: String,
  readonly: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['run'])

let editor

const editorEl = ref()

function initEditor() {
  editor = ace.edit(editorEl.value, {
    mode: 'ace/mode/sql',
    selectionStyle: 'text',
    enableSnippets: true,
    enableBasicAutocompletion: true,
    enableLiveAutocompletion: true,
    fontSize: '14px'
  })
  // editor.setTheme("ace/theme/github")
  // editor.setTheme("ace/theme/solarized_light")
  if (props.code) {
    editor.setValue(props.code)
  }
  if (props.readonly) {
    editor.setReadOnly(true)
  }
  editor.on('change', function(e) {
    editor.execCommand('startAutocomplete')
  })
  window.editor = editor
}

onMounted(() => {
  initEditor()
})

onBeforeUnmount(() => {
  if (!editor) {
    return
  }
  editor.destroy()
  editor.container.remove()
})

watchEffect(() => {
  const content = props.code
  if (!editor) {
    return
  }
  editor.setValue(content)
})

function getValue() {
  return editor.getValue().trim()
}

function getSelected() {
  return editor.getSelectedText().trim()
}

function format() {
  // 格式化选中区域
  const selectedText = getSelected()
  if (selectedText) {
    // 获取当前选中的 Range
    const session = editor.getSession()
    const selection = editor.getSelection()
    const selectedRange = selection.getRange()

    // 替换为新文本
    session.replace(selectedRange, formatter.format(selectedText))

    // 清空选择
    // selection.clearSelection()
    return
  }

  const code = getValue()
  if (code) {
    editor.setValue(formatter.format(code))
  }
}

defineExpose({
  getValue,
  getSelected,
  format
})
</script>

<style>
.cm-editor-container {
  height: 100%;
  overflow: auto;
  background-color: white;
}

.cm-editor {
  height: 100%;
}

.ͼb {
  font-weight: bold;
}
</style>
